/**
 * Created by AllanXu on 7/25/2016.
 */
define(function (require) {
    var Vue = require('vue'),
        Config = require('config'),
        _ = require('ajax'),
        utilities = require('utilities'),
        VueSwipe = require('vueSwipe');
    // console.log(addCode);

    var id = utilities.getParameterByName('id');

	var a1 = document.getElementById('a1')
    if (typeof id !== 'undefined' && id !== '') {https://tinypng.com/
        sessionStorage.setItem('id', id);
    } else {
        if (typeof sessionStorage.id === 'undefined') {
            var els = document.querySelectorAll('*');
            for (var i = 0; i < els.length; i++) {
                els[i].addEventListener('click', function (e) {
                    e.preventDefault();
                    location.href = 'http://friend.jxyouth.org.cn/wxOAuth?appId=wxe9a08de52d2723ba&callBackUrl=phone_bind.html';
                    //location.href = 'phone_bind.html?openId=' + utilities.getParameterByName('openId');
                    //location.href = 'http://friend.jxyouth.org.cn/wxOAuth?appId=wxe9a08de52d2723ba&callBackUrl=phone_bind.html';
                    return false;
                });
            }
        }
    }

//  var speed=50
//   var slide=document.getElementById("slide");
//   var slide2=document.getElementById("slide2");
//   var slide1=document.getElementById("slide1");
//   slide2.innerHTML = slide1.innerHTML
//   function Marquee(){
//       if(slide2.offsetTop-slide.scrollTop<=0)
//           slide.scrollTop-=slide1.offsetHeight
//       else{
//           slide.scrollTop++
//       }
//   }
//   var MyMar=setInterval(Marquee,speed)
//   slide.onmouseover=function(){clearInterval(MyMar)}
//   slide.onmouseout=function(){MyMar=setInterval(Marquee,speed)};

  
  
  

    var app = new Vue({
        el: '#index',
        data: {
            gWidth:0,
            galleryWidth: 0,
            bannerHeight: 0,
            slideHeight: 0,
            authReady: window.authReady,
            theme: window.theme,
            isShow: false,
            isBind: false,
            filterArr:[],
            cityArr:[],
            countyArr:[],
            manData: 100,
            manVipData: 0,
            womanData: 0,
            womanVipData: 0,
            numAddSpeed: 1500,
            a1: a1,
            ageArr: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45],
            num:0,
            keywords:'',
            renderObj: {
                banners: '',
                listArr: [],
                listArr1: [],
                listArr2: [],
                listArr3: [],
                listArr4: [],
                listArr5: [],
                infoArr: []
            },
            marriage:'',
            sex: '',
            type: 3,
            curTab: 0,
            region:'',
            income:'',
            educations:'',
            ageMin: '',
            ageMax: '',
            // 接口参数使用
            selectedAgeMin: '',
            selectedAgeMax: '',
            activityList: [],
            activityPhoto: [],
            // 挑选的市县id
            selectedCityId: '',
            selectedCountyId: '',
            picServer: Config.picServer,
            defaultAdd: '江西省',                        
        },
        components: {
            'swipe': VueSwipe.Swipe,
            'swipe-item': VueSwipe.SwipeItem
        },
        computed: {
        },
  		ready: function () {
  			console.log('223')
  			
  		},
  		attached: function () {
  			console.log(456)
  			
  		},
  		compiled: function () {
  			
  		},
        watch: {
        	
            // 选择城市
            selectedCityId: function () {
                //console.log(111);
                app.region = app.selectedCityId;
                app.selectCounty();
            },
            // 选择县
            selectedCountyId: function () {
                app.region = app.selectedCountyId;
            },
            // 选择最小年龄
            ageMin: function () {
                //console.log(1);
                if(app.ageMax!==''){
                    if (app.ageMax < app.ageMin) {
                        app.selectedAgeMax = app.ageMin;
                        app.selectedAgeMin = app.ageMax;
                        //console.log("最小:",app.selectedAgeMin,"最大:", app.selectedAgeMax);
                    }
                }else{
                    app.selectedAgeMin = app.ageMin;
                }
                //console.log(app.selectedAgeMin, app.selectedAgeMax,1)
            },
            // 选择最大年龄
            ageMax: function () {
                if(app.ageMin!==''){
                    if (app.ageMax < app.ageMin) {
                        app.selectedAgeMax = app.ageMin;
                        app.selectedAgeMin = app.ageMax;
                        //console.log("最小:",app.selectedAgeMin,"最大:", app.selectedAgeMax);
                    }else{
                        app.selectedAgeMax = app.ageMax;
                    }
                }else{
                    app.selectedAgeMax = app.ageMax;
                }

                //console.log(app.selectedAgeMin, app.selectedAgeMax,2)
            },
        },
        methods: {
        	
            selectCounty: function () {
                // 居住地
                _(Config.SERVICE.MATES.ADDR + '?parentId=' + app.selectedCityId, {}, function (data) {
                    //console.log(data);
                    app.countyArr = data.obj[app.selectedCityId];
                });
            },
            init: function () {
            	// 会员数           	
                _(Config.SERVICE.INDEX.WXHYCOUNT,
                    {},
                    function (data) {
                        console.log(data.obj.rs1, 'yuanyuanshu')
                        app.manData = data.obj.rs1;
                        app.manVipData = data.obj.rzs1;
                        app.womanData = data.obj.rs2;
                        app.womanVipData = data.obj.rzs2;
                        document.getElementById('t1').setAttribute('data-to', app.manData)
                        document.getElementById('t1').setAttribute('data-speed', app.numAddSpeed)
//                      document.getElementById('t2').setAttribute('data-to', app.manVipData)
//                      document.getElementById('t2').setAttribute('data-speed', app.numAddSpeed)
                        document.getElementById('t3').setAttribute('data-to', app.womanData)
                        document.getElementById('t3').setAttribute('data-speed', app.numAddSpeed)
//                      document.getElementById('t4').setAttribute('data-to', app.womanVipData)
//                      document.getElementById('t4').setAttribute('data-speed', app.numAddSpeed)
                        $.fn.countTo = function(a) {
a = a || {};
return $(this).each(function() {
   var c = $.extend({},
   $.fn.countTo.defaults, {
    from: $(this).data("from"),
    to: $(this).data("to"),
    speed: $(this).data("speed"),
    refreshInterval: $(this).data("refresh-interval"),
    decimals: $(this).data("decimals")
   }, a);
var h = Math.ceil(c.speed / c.refreshInterval),
i = (c.to - c.from) / h;
var j = this,
f = $(this),
e = 0,
g = c.from,
d = f.data("countTo") || {};
f.data("countTo", d);
if (d.interval) {
   clearInterval(d.interval)
}
d.interval = setInterval(k, c.refreshInterval);
b(g);
function k() {
   g += i;
   e++;
   b(g);
   if (typeof(c.onUpdate) == "function") {
    c.onUpdate.call(j, g)
   }
   if (e >= h) {
    f.removeData("countTo");
    clearInterval(d.interval);
    g = c.to;
    if (typeof(c.onComplete) == "function") {
     c.onComplete.call(j, g)
    }
   }
}
function b(m) {
   var l = c.formatter.call(j, m, c);
   f.html(l)
}
   })
};
$.fn.countTo.defaults = {
from: 0,
to: 0,
speed: 10,
refreshInterval: 10,
decimals: 0,
formatter: formatter,
onUpdate: null,
onComplete: null
};
function formatter(b, a) {
return b.toFixed(0)
}
$("#count-number").data("countToOptions", {
formatter: function(b, a) {
   return b.toFixed(0).replace(/\B(?=(?:\d{3})+(?!\d))/g, ",")
}
});
$(".timer").each(count);
function count(a) {
var b = $(this);
a = $.extend({},
a || {},
b.data("countToOptions") || {});
b.countTo(a)
};
                    }
                );
                // 婚姻状态
                _(Config.DICTIONARY + '?parentId=340,8,418,2,6', {}, function (data) {
                    app.filterArr = data.obj;
                });
                // 居住地
                _(Config.SERVICE.MATES.ADDR + '?parentId=2', {}, function (data) {
                    app.cityArr = data.obj[2];
                });

                var mySwipe = new Swipe(document.getElementById('slider'), {
                    autoplay:false
                });

                var mySwipes = new Swipe(document.getElementById('sliders'), {
                    autoplay:false
                });
                //swipe({
                 //   auto: 4000
               // });
                app.gWidth = (document.body.clientWidth - 60);
                app.galleryWidth = (document.body.clientWidth - 60) / 3;
                app.bannerHeight = document.body.clientWidth / 1.8;
                // console.log(JSON.parse(JSON.stringify(xxxx)));
                // 获取右上角地区
                var addName = sessionStorage.getItem('addName');
                app.defaultAdd = addName || app.defaultAdd;

                // 用户信息获取( 首页存到sessionStorage，其他页面直接取 )
                utilities.refreshUserInfo(function (data) {
                    // app.renderObj = data;
                });
                // 轮播图
                _(Config.SERVICE.INDEX.BANNER,
                    {},
                    function (data) {
                        //console.log(data, 2333);
                        app.renderObj.banners = data.obj;
                    });
                // 优质会员
                //  会员数               
                _(Config.SERVICE.INDEX.LIST + '?pagesize=9&xgmember.sex=&xgmate.type=1&code=' + addCode,
                    {},                   
                    function (data) {
                        app.renderObj.listArr1 = data.pageitems;
                        console.log(app.renderObj.listArr1.length)
                        console.log(app.renderObj.listArr1)
                      	Vue.nextTick(function () {
                        if(app.renderObj.listArr1.length > 4) {
                        $("#a1").scrollForever({
                                dir: 'left',
  								continuous: true
  							});
                        }
                      	})
                    });

                _(Config.SERVICE.INDEX.LIST + '?pagesize=9&xgmember.sex=&xgmate.type=2&code=' + addCode,
                    {},
                    function (data) {
                        app.renderObj.listArr2 = data.pageitems;
                        console.log(app.renderObj.listArr2.length)
                        console.log($(window).width())                        
                        Vue.nextTick(function () {
                        if(app.renderObj.listArr2.length > 4) {
                        $("#a2").scrollForever({
//								dir: 'left',
//								continuous: true,
//								num: 2,
//								speed: 2000,
//								delayTime: 5000
                                dir: 'left',
  								continuous: true
  							});
                        }
                        });                       
                    });
                _(Config.SERVICE.INDEX.LIST + '?pagesize=9&xgmember.sex=&xgmate.type=3&code=' + addCode,
                    {},
                      function (data) {
                        app.renderObj.listArr3 = data.pageitems;
                        console.log(app.renderObj.listArr3.length)
                        Vue.nextTick(function () {
                        if(app.renderObj.listArr3.length > 4) {
                        $("#a3").scrollForever({
//								dir: 'left',
//								continuous: true,
//								num: 2,
//								speed: 2000,
//								delayTime: 5000
                                dir: 'left',
  								continuous: true
  							});
                        }
                        });                       
                    });
                _(Config.SERVICE.INDEX.LIST + '?pagesize=9&xgmember.sex=403&code=' + addCode,
                    {},
                    function (data) {
                        app.renderObj.listArr4 = data.pageitems;
                    });
                _(Config.SERVICE.INDEX.LIST + '?pagesize=9&xgmember.sex=402&code=' + addCode,
                    {},
                    function (data) {
                        app.renderObj.listArr5 = data.pageitems;
                    });
                // 交友活动
                _(Config.SERVICE.INDEX.INFOLIST + '?id=' + sessionStorage.id + '&pagesize=3' + '&code=' + addCode,
                    {},
                    function (data) {
                        // app.renderObj.listArr = data.pageitems;
                        app.renderObj.infoArr = data.pageitems;
                        //console.log(data, 4555)
                    }
                );
                // 各地动态
                _(Config.SERVICE.ACTIVITY.LIST + '?id=' + sessionStorage.id + '&pagesize=4' + '&code=' + addCode,
                    {},
                    function (data) {
                        //console.log(data, 23)
                        app.activityList = data.pageitems;
                        // app.renderObj.listArr = data.pageitems;
                        // app.renderObj.infoArr = data.pageitems;
                    }
                );
                
                 // 说说间隔滚动
                _(Config.SERVICE.INDEX.MYMOOD,{
                    "pagesize": 12,
                    "pageno": 1,
                    "code": addCode
                }, function (data) {
                       console.log(data, 'da');
                    if (app.pageno == 1) {
                        app.renderObj.listArr = data.pageitems;
                        
                    } else {
                        app.renderObj.listArr = app.renderObj.listArr.concat(data.pageitems);
                    }
                    Vue.nextTick(function () {
                        if(app.renderObj.listArr.length > 1) {
                        	$("#ff").scrollForever({
  								dir: 'top',
  								continuous: false,
  								num: 1,
  								speed: 1000,
								delayTime: 4000,
  								container: ".ff_listOne_box",
  								innner: ".ff_listOne"
  							});
                        }
                        });                     
                });
                
                
                // 活动图片
                _(Config.SERVICE.INDEX.PHOTOLIST, {
                    "pagesize": 7,
                    "pageno": 1,
                    "code": addCode
                }, function (data) {
                    //console.log(data);
                    app.activityPhoto = data.pageitems;
                });
                //定位
                _(Config.SERVICE.COMMON.WX_SIGN, {
                    'url': encodeURIComponent(location.href)
                }, function (data) {
                    wx.ready(function () {
                        wx.getLocation({
                            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                            success: function (res) {
                                //console.log("进入")
                                if (res.errMsg == 'getLocation:ok') {
                                    _(Config.SERVICE.COMMON.GET_AREA, {
                                        id: sessionStorage.id,
                                        //id:id,
                                        latitude: res.latitude,
                                        longitude: res.longitude,
                                        precision: res.accuracy
                                    }, function (data) {
                                        var addCode = sessionStorage.getItem("addCode");
                                        if(data.obj.code!='36'){
                                           sessionStorage.setItem('addName', data.obj.name);
                                           sessionStorage.setItem('addCode', data.obj.code);
                                        }
                                    });
                                }
                            }
                        });
                    });
                    wx.config({
                        debug: false,
                        appId: data.obj.appid,
                        timestamp: data.obj.timestamp,
                        nonceStr: data.obj.nonceStr,
                        signature: data.obj.signature,
                        jsApiList: ['getLocation']
                    });
                });
                
            },


            confirmFilter:function(){
                location.href = "friend_index.html?sex="+app.sex+"&marriage="+app.marriage+"&selectedAgeMax="+app.selectedAgeMax+"&selectedAgeMin="+app.selectedAgeMin+"&educations="+app.educations+"&income="+app.income+"&region="+app.region;
            },
            // 活动详情
            goDetail: function (id) {
                location.href = "friend_detail.html?id=" + id;
            },
            // 交友活动详情
            goMateDetail: function (id) {
                location.href = "activity_detail.html?typeId=" + id;
            },
            // 信息详情
            goInfoDetail: function (id) {
                location.href = "info_detail.html?id=" + id;
            },
            // 活动图片点击
            goActivityPhoto: function (id) {
                location.href = "activity_photo_detail.html?id=" + id;
            },
            goNum:function (num) {
                app.num=num;
            },
            search:function(){
                if(app.keywords==''){
                    alert("请输入会员ID");
                    return;
                }
                if(isNaN(app.keywords)){
                    alert("输入的会员ID格式有误");
                    return;
                }
                _(Config.SERVICE.MATES.DETAILS + '?id=' + app.keywords + '&xgmember.id=' + sessionStorage.id, {}, function (data) {
                    if(data.code==500)
                        alert(data.errmsg);
                    else
                        location.href = "friend_detail.html?id=" + app.keywords;
                });
            }
        }
    });

    var addCode = sessionStorage.getItem("addCode");
    if (addCode == null) {
        sessionStorage.setItem('addName', '江西省');
        sessionStorage.setItem('addCode', 36);
    }
    addCode = sessionStorage.getItem("addCode");
    
    app.init();


   /* if (addCode !== null) {
        app.init();
    } else {
        _(Config.SERVICE.COMMON.WX_SIGN, {
            'url': encodeURIComponent(location.href)
        }, function (data) {
            console.log(data);
            wx.ready(function () {
                wx.getLocation({
                    type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    success: function (res) {
                        console.log("进入")
                        if (res.errMsg == 'getLocation:ok') {
                            _(Config.SERVICE.COMMON.GET_AREA, {
                                id: sessionStorage.id,
                                //id:id,
                                latitude: res.latitude,
                                longitude: res.longitude,
                                precision: res.accuracy
                            }, function (data) {
                                sessionStorage.setItem('addName', data.obj.name);
                                sessionStorage.setItem('addCode', data.obj.code);
                                if (location.search === '') {
                                    location.href = location.href + '?v=' + (new Date()).getTime();
                                } else {
                                    location.href = location.href + '&v=' + (new Date()).getTime();
                                }
                            });
                        } else {
                            alert('位置获取失败！');
                            sessionStorage.setItem('addCode', 33);
                            if (location.search === '') {
                                location.href = location.href + '?v=' + (new Date()).getTime();
                            } else {
                                location.href = location.href + '&v=' + (new Date()).getTime();
                            }
                        }
                    }
                });
            });
            wx.config({
                debug: false,
                appId: data.obj.appid,
                timestamp: data.obj.timestamp,
                nonceStr: data.obj.nonceStr,
                signature: data.obj.signature,
                jsApiList: ['getLocation']
            });
        });
    }*/
   
//

});